package internal.memory.management.example;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;
import internal.memory.management.example.R;

public class InternalMemoryManagementExampleActivity extends Activity {
	
	private String fichero = "foo";
	private EditText editor;
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
	
		super.onCreate(savedInstanceState);
		setContentView(R.layout.editor);
		editor = (EditText) findViewById(R.id.EditText);
		String texto = loadData();
		editor.setText(texto);
	}
	
	/**
	 * This method reads a file and returns its contents as a String
	 * 
	 * @return The String object containing the text in the file
	 */
	protected String loadData() {
	
		FileInputStream fis = null;
		String texto = "";
		
		try {
			//open the file
			fis = openFileInput(fichero);
			InputStreamReader reader = new InputStreamReader(fis);
			BufferedReader buffreader = new BufferedReader(reader);
			String linea = "";
			//read lines til there are any and append them to final string
			try {
				while ((linea = buffreader.readLine()) != null) {
					texto += linea + "\n";
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} 
		catch (FileNotFoundException e) {
			Toast.makeText(this, "Error al leer el fichero", Toast.LENGTH_LONG).show();
			texto = "Nada";
		} 
		finally {
			
			try {
				if (fis!=null)
					fis.close();
			} 
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		return texto;
	}
	
	/**
	 * onStop() - Get text inserted and save it to file
	 */
	@Override
	protected void onStop() {
		String texto = editor.getText().toString();
		saveData(texto);
		super.onStop();
	}
	
	/**
	 * Guarda los datos en la memoria interna
	 * 
	 * @param	texto	The String to be saved in a text file
	 * 
	 */
	protected void saveData(String texto) {
		
		FileOutputStream fos = null;
		try {
			//open file and write the string in it
			fos = openFileOutput(fichero, Context.MODE_PRIVATE);
			fos.write(texto.getBytes());
		} 
		catch (Exception e) {
			Toast.makeText(this, "Error al guardar el fichero", Toast.LENGTH_LONG).show();
		} 
		finally {
			
			try {
				Toast.makeText(this, "Fichero guardado correctamente", Toast.LENGTH_LONG).show();
				fos.close();
			} 
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}